﻿angular.module('app.myinvoices', ['ui.grid.edit'])
.config(['$routeProvider', function ($routeProvider) {
    $routeProvider
        .when('/myinvoices', {
            templateUrl: 'app/myinvoices/myinvoices.tpl.html',
            controller: 'myinvoicesCtrl',
            resolve: {
            }
        });
}])
.controller('myinvoicesCtrl',
    ['$scope',  'modalService', '$interval', 'invoiceProxy', '$routeParams', 'mailProxy','customerPaymentbankProxy',
    'customerPaymentcircleProxy', 'collectorSoaProxy', 'generateSOAProxy', 'contactCustomerProxy','baseDataProxy',
    'APPSETTING', 'siteProxy', 'uiGridConstants', 'dunningProxy', 'commonProxy','myinvoicesProxy','permissionProxy',
    function ($scope,  modalService, $interval, invoiceProxy, $routeParams, mailProxy,customerPaymentbankProxy,
    customerPaymentcircleProxy, collectorSoaProxy,  generateSOAProxy, contactCustomerProxy,baseDataProxy,
    APPSETTING, siteProxy, uiGridConstants, dunningProxy, commonProxy, myinvoicesProxy, permissionProxy
    ) {

        //##########################
        //init parameter
        //##########################
        $scope.floatMenuOwner = ['allinfoCtrl'];
        $scope.maxSize = 10; //paging display max
        $scope.slexecute = 15;  //init paging size(ng-model)
        $scope.iperexecute = 15;   //init paging size(parameter)
        $scope.curpexecute = 1;     //init page
        $scope.totalNum = "";
        $scope.displayClosed = 0;

        $scope.levelList = [
                    { "id": 15, "levelName": '15' },
                    { "id": 500, "levelName": '500' },
                    { "id": 1000, "levelName": '1000' },
                    { "id": 2000, "levelName": '2000' },
                    { "id": 5000, "levelName": '5000' },
                    { "id": 999999, "levelName": 'ALL' }
        ];
        $scope.displaylist = [
                    { "id": 0, "detailName": 'No' },
                    { "id": 1, "detailName": 'Yes' },
                    { "id": 2, "detailName": 'All' }
        ];

        var order = "&$orderby= CustomerNum asc,InvoiceDate asc";
        var filstr = "";

        $scope.DateInt = function () {
            var date = new Date();
            var currentDate = new Date(date.getFullYear(), date.getMonth() + 1, date.getDate());
            $scope.currentDate = currentDate;
        }

        $scope.invoiceList = {
            showGridFooter: true,
            enableFiltering: false,
            columnDefs: [
                        {
                            field: 'invoiceNum', name: 'tmp', displayName: 'Invoice #', enableCellEdit: false, width: '100', pinnedLeft: true
                            , cellTemplate: '<div style="height:30px;vertical-align:middle"><a style="line-height:28px" ng-click="grid.appScope.openInvoiceH(row.entity.invoiceNum)">{{row.entity.invoiceNum}}</a></div>'
                        },
                        { field: 'customerNum', enableCellEdit: false, displayName: 'Customer #', width: '100' },
                        { field: 'customerName', enableCellEdit: false, displayName: 'Customer Name', width: '100' },
                        { field: 'groupCode', enableCellEdit: false, displayName: 'Factory Group Code', width: '100' },
                        { field: 'groupName', enableCellEdit: false, displayName: 'Factory Group Name', width: '100' },
                        { field: 'legalEntity', enableCellEdit: false, displayName: 'Legal Entity', width: '100' },
                        { field: 'teamName', enableCellEdit: false, displayName: 'Team', width: '100' },
                        { field: 'collector', enableCellEdit: false, displayName: 'Collector', width: '100' },
                        { field: 'invoiceDate', enableCellEdit: false, displayName: 'Invoice Date', cellFilter: 'date:\'yyyy-MM-dd\'', width: '100' },
                        { field: 'creditTrem', enableCellEdit: false, displayName: 'Credit Term', width: '100' },
                        { field: 'dueDate', enableCellEdit: false, displayName: 'Due Date', cellFilter: 'date:\'yyyy-MM-dd\'', width: '100' },
                        { field: 'poNum', enableCellEdit: false, displayName: 'PO Num', width: '120' },
                        { field: 'soNum', enableCellEdit: false, displayName: 'SO Num', width: '120' },
                        { field: 'mstCustomer', enableCellEdit: false, displayName: 'RBO', width: '120' },
                        { field: 'currency', enableCellEdit: false, displayName: 'Currency', width: '90' },
                        { field: 'country', enableCellEdit: false, displayName: 'Country', width: '90' },
                        {
                            field: 'balanceAmt', enableCellEdit: false, displayName: 'Outstanding Invoice Amount', cellFilter: 'number:2', type: 'number', width: '200'
                            , cellClass: function (grid, row, col, rowRenderIndex, colRenderIndex) {
                                if (parseFloat(grid.getCellValue(row, col)) < 0) {
                                    return 'uigridred';
                                }
                            }
                        },
                        {
                            field: 'originalAmt', enableCellEdit: false, displayName: 'Original Invoice Amount', cellFilter: 'number:2', type: 'number', width: '200'
                            , cellClass: function (grid, row, col, rowRenderIndex, colRenderIndex) {
                                if (parseFloat(grid.getCellValue(row, col)) < 0) {
                                    return 'uigridred';
                                }
                            }
                        },
                        {
                            field: 'dayLate', displayName: 'Days Late', enableCellEdit: false, width: '80', type: 'number'
                            //,cellTemplate: '<div style="height:30px;vertical-align:middle">{{grid.appScope.calDaysLate(row.entity)}}</div>'
                        },
                        {
                            field: 'states', enableCellEdit: false, displayName: 'Status', width: '80'
                            , cellClass: function (grid, row, col, rowRenderIndex, colRenderIndex) {
                                if (grid.getCellValue(row, col) === '004004') {
                                    return 'uigridred';
                                }
                            }
                            , filter: {
                                term: '',
                                type: uiGridConstants.filter.SELECT,
                                selectOptions: [
                                    { value: '004001', label: 'Open' },
                                    { value: '004002', label: 'PTP' },
                                    { value: '004003', label: 'Paid' },
                                    { value: '004004', label: 'Dispute' },
                                    { value: '004005', label: 'Cancelled' },
                                    { value: '004006', label: 'Uncollectable' },
                                    { value: '004007', label: 'WriteOff' },
                                    { value: '004008', label: 'PartialPay' },
                                    { value: '004010', label: 'Broken PTP' },
                                    { value: '004009', label: 'Closed' },
                                    { value: '004011', label: 'Hold' },
                                    { value: '004012', label: 'Payment' }]
                            }
                            ,cellFilter: 'mapStatus'
                        },
                        {
                            field: 'trackStates', enableCellEdit: false, displayName: 'Invoice Track', width: '100'
                            , filter: {
                                term: '',
                                type: uiGridConstants.filter.SELECT,
                                selectOptions: [
                                    { value: '001', label: 'SOA Sent' },
                                    { value: '002', label: 'Second Reminder Sent' },
                                    { value: '003', label: 'Final Reminder Sent' },
                                    { value: '004', label: 'Dispute' },
                                    { value: '005', label: 'PTP' },
                                    { value: '006', label: 'Payment Notice Received' },
                                    { value: '007', label: 'Broken PTP' },
                                    { value: '008', label: 'First Broken Sent' },
                                    { value: '009', label: 'Second Broken Sent' },
                                    { value: '011', label: 'Hold' },
                                    { value: '012', label: 'Agency Sent' },
                                    { value: '013', label: 'Write Off' },
                                    { value: '014', label: 'Paid' },
                                    { value: '015', label: 'Bad Debit' },
                                    { value: '016', label: 'Open' },
                                    { value: '017', label: 'Close' },
                                    { value: '018', label: 'Contra' },
                                    { value: '019', label: 'Breakdown' }
                                ]
                            }
                            ,cellFilter: 'mapTrack'
                        },
                        { field: 'ptpDate', enableCellEdit: false, displayName: 'PTP Date', cellFilter: 'date:\'yyyy-MM-dd\'', width: '100' },
                        {
                            field: 'class', enableCellEdit: false, displayName: 'Document Type', width: '120'
                            , filter: {
                                term: '',
                                type: uiGridConstants.filter.SELECT,
                                selectOptions: [
                                    { value: 'DM', label: 'DM' },
                                    { value: 'CM', label: 'CM' },
                                    { value: 'INV', label: 'INV' },
                                    { value: 'Payment', label: 'Payment' }]
                            }
                            ,cellFilter: 'mapClass'
                        },
                        {
                            field: 'comments', name: 'tmp1', enableCellEdit: false, displayName: 'Invoice Memo', width: '120',
                            cellTemplate: '<div><a class="glyphicon glyphicon-pencil" ng-click="grid.appScope.editMemoShow(row.entity.id,row.entity.invoiceNum,row.entity.comments)"></a>'
+ '<label id="lbl{{row.entity.id}}" ng-mouseMove="grid.appScope.memoShow(row.entity.invoiceNum,row.entity.comments,$event)" ng-mouseOut="grid.appScope.memoHide()">{{row.entity.comments.substring(0,7)}}...</label></div>'
                        }
                        ],
                        onRegisterApi: function (gridApi) {
                            $scope.gridApi = gridApi;

                            gridApi.selection.on.rowSelectionChanged($scope, function (row) {
                                if (row.entity.id != 0) {
                                    $scope.invoiceSum();
                                }
                            });
                            gridApi.selection.on.rowSelectionChangedBatch($scope, function (rows) {
                                $scope.invoiceSumBatch();
                            });
                        }
        }

        //##########################
        //init && search
        //##########################
        $scope.init = function () {
            myinvoicesProxy.invoicePaging(1, 15, order + "&closeType=0" + filstr, function (list) {
                $scope.invoiceList.data = list[0].results;
                $scope.ttexecute = list[0].count;
                $scope.totalNum = list[0].count;
                //float menu 加载 
                $scope.calculate($scope.curpexecute, $scope.iperexecute, list[0].results.length);
                $scope.$broadcast("FLOAT_MENU_REFRESH", $scope.floatMenuOwner[0]);
            }, function (error) { alert(error); })
        }

        //************************** get current date ***********************
        $scope.DateInt();

        //*********************** openfilter ***********************
        var isShow = 0; //0:hide;1:show
        var baseFlg = true;
        $scope.showCollector = false;
        $scope.openFilter = function () {

            //*************************aging filter base binding*****************************s
            if (baseFlg) {
                baseDataProxy.SysTypeDetails("004,029,031", function (res) {
                    angular.forEach(res, function (r) {
                        $scope.istatuslist = r["004"];
                        $scope.invoiceTrackStates = r["029"];
                        $scope.docuTypelist = r["031"];
                        //$scope.displaylist = r["032"];
                    });
                });
                //Legal Entity DropDownList binding
                siteProxy.Site("", function (legal) {
                    $scope.legallist = legal;
                });
                permissionProxy.getCurrentUser("dummy", function (user) {
                    if (user.actionPermissions.indexOf('alldataforsupervisor') >= 0) {
                        $scope.showCollector = true;
                        //Collector List
                        permissionProxy.query({ 'getCollectList': 'dummy' }, function (res) {
                            $scope.collectorList = res;
                        })
                    }
                })
            }
            //*************************aging filter base binding*****************************e

            if (isShow == 0) {
                $("#divAgingSearch").show();
                isShow = 1;
                baseFlg = false;
            } else if (isShow == 1) {
                $("#divAgingSearch").hide();
                isShow = 0;
                baseFlg = false;
            }
        }

        $scope.searchCollection = function () {
            filstr = buildFilter();

            var index = 1;
            $scope.curpexecute = 1;     //init page
            myinvoicesProxy.invoicePaging(index, $scope.iperexecute, filstr, function (list) {
                $scope.invoiceList.data = list[0].results;
                $scope.ttexecute = list[0].count;
                $scope.totalNum = list[0].count;
                $scope.calculate($scope.curpexecute, $scope.iperexecute, list[0].results.length);
            });
        }

        //reset Search conditions
        $scope.resetSearch = function () {
            filstr = "";
            $scope.custCode = "";
            $scope.custName = "";
            $scope.billGroupCode = "";
            $scope.billGroupName = "";

            $scope.invoiceNum = "";
            $scope.poNum = "";
            $scope.soNum = "";
            $scope.rbo = "";
            $scope.creditTerm = "";

            $scope.displayClosed = 0;
            $scope.legal = "";
            $scope.docuType = "";
            $scope.states = "";
            $scope.trackStates = "";

            $scope.memo = "";
            $scope.collector = "";
            $scope.ptpDateF = "";
            $scope.ptpDateT = "";
            $scope.invoiceDateF = "";
            $scope.invoiceDateT = "";
            $scope.dueDateF = "";
            $scope.dueDateT = "";

        }

        buildFilter = function () {
            //multi-conditions
            var filterStr = "";
            filterStr += order + "&$filter=(InvoiceNum ne '')";

            //row one
            if ($scope.custCode) {
                filterStr += " and (contains(CustomerNum,'" + encodeURIComponent($scope.custCode) + "'))";
            }

            if ($scope.custName) {
                filterStr += " and (contains(CustomerName,'" + encodeURIComponent($scope.custName) + "'))"
            }

            if ($scope.billGroupCode) {
                filterStr += " and (contains(GroupCodeOld,'" + encodeURIComponent($scope.billGroupCode) + "'))";
            }

            if ($scope.billGroupName) {
                filterStr += " and (contains(GroupNameOld,'" + encodeURIComponent($scope.billGroupName) + "'))";
            }

            //row two
            if ($scope.invoiceNum) {
                filterStr += " and (contains(InvoiceNum,'" + encodeURIComponent($scope.invoiceNum) + "'))";
            }

            if ($scope.poNum) {
                filterStr += " and (contains(PoNum,'" + encodeURIComponent($scope.poNum) + "'))";
            }

            if ($scope.soNum) {
                filterStr += " and (contains(SoNum,'" + encodeURIComponent($scope.soNum) + "'))";
            }

            if ($scope.rbo) {
                filterStr += " and (contains(MstCustomer,'" + encodeURIComponent($scope.rbo) + "'))";
            }

            if ($scope.creditTerm) {
                filterStr += " and (contains(CreditTrem,'" + encodeURIComponent($scope.creditTerm) + "'))";
            }

            //row three
            if ($scope.legal) {
                filterStr += " and (LegalEntity eq '" + $scope.legal + "')";
            }

            if ($scope.docuType) {
                filterStr += " and (Class eq '" + $scope.docuType + "')";
            }

            if ($scope.states) {
                filterStr += " and (States eq '" + $scope.states + "')";
            }

            if ($scope.trackStates) {
                filterStr += " and (TrackStates eq '" + $scope.trackStates + "')";
            }

            //row four
            if ($scope.memo) {
                filterStr += " and (contains(Comments,'" + encodeURIComponent($scope.memo) + "'))";
            }

            if ($scope.collector) {
                filterStr += " and (contains(Collector,'" + encodeURIComponent($scope.collector) + "'))";
            }

            if ($scope.ptpDateF) {
                filterStr += "and (PtpDate ge " + $scope.ptpDateF + ")";
            }

            if ($scope.ptpDateT) {
                filterStr += "and (PtpDate le " + $scope.ptpDateT + ")";
            }

            //row five
            if ($scope.invoiceDateF) {
                filterStr += "and (InvoiceDate ge " + $scope.invoiceDateF + ")";
            }

            if ($scope.invoiceDateT) {
                filterStr += "and (InvoiceDate le " + $scope.invoiceDateT + ")";
            }

            if ($scope.dueDateF) {
                filterStr += "and (DueDate ge " + $scope.dueDateF + ")";
            }

            if ($scope.dueDateT) {
                filterStr += "and (DueDate le " + $scope.dueDateT + ")";
            }

            //GroupName
            //if ($scope.billGroupName) {
            //    filterStr = "&groupName=" + $scope.billGroupName + filterStr;
            //} else {
            //    filterStr = "&groupName=" + filterStr;
            //}

            //Display Closed
            filterStr = "&closeType=" + $scope.displayClosed + filterStr;
            //if ($scope.displayClosed) {
            //    filterStr = "&closeType=" + $scope.displayClosed + filterStr;
            //} else {
            //    filterStr = "&closeType=" + filterStr;
            //}

            return filterStr;
        };


        //##########################
        //export
        //##########################

        $scope.export = function () {
            

            window.location = APPSETTING['serverUrl'] + '/api/myinvoices?' +
                'cCode=' + $scope.custCode + '&cName=' + $scope.custName + '&bCode=' + $scope.billGroupCode + '&bName=' + $scope.billGroupName +
                '&iNum=' + $scope.invoiceNum + '&pNum=' + $scope.poNum + '&sNum=' + $scope.soNum + '&rbo=' + $scope.rbo + '&cTerm=' + $scope.creditTerm +
                '&close=' + $scope.displayClosed + '&legal=' + $scope.legal + '&doc=' + $scope.docuType + '&state=' + $scope.states + '&tstate=' + $scope.trackStates +
                '&memo=' + $scope.memo + '&oper=' + $scope.collector +'&pdf=' + $scope.ptpDateF + '&pdt=' + $scope.ptpDateT + '&idf=' + $scope.invoiceDateF + '&idt=' + $scope.invoiceDateT +
                '&ddf=' + $scope.dueDateF + '&ddt=' + $scope.dueDateT;
        }

        //################################################################
        //change page size && change page && calculate page parameter
        //################################################################
        //paging size change
        $scope.pschangeexecute = function (slexecute) {
            var index = 1;
            $scope.curpexecute = 1;     //init page
            filstr = buildFilter();
            myinvoicesProxy.invoicePaging(index, slexecute, filstr, function (list) {
                $scope.invoiceList.data = list[0].results;
                $scope.iperexecute = slexecute;
                $scope.ttexecute = list[0].count;
                $scope.totalNum = list[0].count;
                $scope.calculate($scope.curpexecute, $scope.iperexecute, list[0].results.length);
            });
        };

        //paging change
        $scope.executepChanged = function () {

            var index = $scope.curpexecute;
            filstr = buildFilter();
            myinvoicesProxy.invoicePaging(index, $scope.iperexecute, filstr, function (list) {
                $scope.invoiceList.data = list[0].results;
                $scope.ttexecute = list[0].count;
                $scope.totalNum = list[0].count;
                $scope.calculate($scope.curpexecute, $scope.iperexecute, list[0].results.length);
            }, function (error) {
                alert(error);
            });
        };

        //calculate page parameter
        $scope.calculate = function (currentPage, itemsperpage, count) {
            if (count == 0) {
                $scope.fromItem = 0;
            } else {
                $scope.fromItem = (currentPage - 1) * itemsperpage + 1;
            }
            $scope.toItem = (currentPage - 1) * itemsperpage + count;
        }


        //##########################
        //change invoice status
        //##########################
        $scope.changetab = function (type) {
            //get selected invoiceIds
            $scope.inv = [];

            angular.forEach($scope.gridApi.selection.getSelectedRows(), function (rowItem) {
                if (rowItem.id != 0) {
                    $scope.inv.push(rowItem.id);

                }
            });

            if ($scope.inv == "" || $scope.inv == null) {
                alert("Please choose 1 invoice at least .")
                return;
            }

            if (type == "dispute") {

                //var relatedMail = "";
                //relatedMail = $scope.mailInstance.from + "  " + $scope.mailInstance.subject + " " + $scope.mailInstance.createTime.replace("T", " ");

                contactHistoryProxy.queryObject({ type: 'dispute' }, function (disInvInstance) {
                    disInvInstance["title"] = "Dispute Reason";
                    var modalDefaults = {
                        templateUrl: 'app/common/contactdetail/contact-dispute.tpl.html',
                        controller: 'contactDisputeCtrl',
                        size: 'lg',
                        resolve: {
                            disInvInstance: function () { return disInvInstance; },
                            custnum: function () { return ""; },
                            invoiceIds: function () { return $scope.inv; },
                            contactId: function () { return ""; },
                            relatedEmail: function () { return ""; },
                            contactPerson: function () { return ""; }
                        },
                        windowClass: 'modalDialog'
                    };
                    modalService.showModal(modalDefaults, {}).then(function (result) {
                        if (result == "submit") {
                        }
                    });
                });
            } else if (type == "ptp") {

                var modalDefaults = {
                    templateUrl: 'app/common/contactdetail/contact-ptp.tpl.html',
                    controller: 'contactPtpCtrl',
                    size: 'lg',
                    resolve: {
                        custnum: function () {
                            return "";
                        },
                        invoiceIds: function () {
                            return $scope.inv;
                        },
                        contactId: function () {
                            return "";
                        },
                        relatedEmail: function () {
                            return "";
                        },
                        contactPerson: function () {
                            return "";
                        }
                    },
                    windowClass: 'modalDialog'
                };
                modalService.showModal(modalDefaults, {}).then(function (result) {
                    if (result[0] == "submit") {
                        $scope.refreshListVal("004002", "005", result[1], result[2]);
                    }
                });
            } else if (type == "notice") {

                var modalDefaults = {
                    templateUrl: 'app/common/contactdetail/contact-notice.tpl.html',
                    controller: 'contactNoticeCtrl',
                    size: 'lg',
                    resolve: {
                        custnum: function () {
                            return "";
                        },
                        invoiceIds: function () {
                            return $scope.inv;
                        },
                        contactId: function () {
                            return "";
                        },
                        relatedEmail: function () {
                            return "";
                        },
                        contactPerson: function () {
                            return "";
                        }
                    },
                    windowClass: 'modalDialog'
                };
                modalService.showModal(modalDefaults, {}).then(function (result) {
                    if (result[0] == "submit") {
                        $scope.refreshListVal("004012", result[1], result[2], null);
                    }
                });
            }
        }


        $scope.init();


        //##########################
        //invoice memo edit
        //##########################
        //********************** edit one memo //**********************s
        $scope.editMemoShow = function (invoiceId, invoiceNum, memo) {
            if (invoiceId != 0) {
                $scope.selectText = memo;
                var h = document.documentElement.clientHeight;
                var w = document.documentElement.clientWidth;
                var content = document.getElementById('boxEdit');
                var contentWidth = $('#boxEdit').css('width').replace('px', '');
                var contentHeight = $('#boxEdit').css('height').replace('px', '');
                var stop = self.pageYOffset;
                var sleft = self.pageXOffset;
                var left = w / 2 - contentWidth / 2 + sleft;
                var top = h / 2 - contentHeight / 2 + stop;
                $('#boxEdit').css({ 'left': left + 'px', 'top': top + 'px' });
                $('#txtBox').css({ 'width': contentWidth - 20 + 'px', 'height': contentHeight - 100 + 'px' });
                var str = '';
                var str1 = '';
                str = 'Invoice :"' + invoiceNum + '" Memo : ';
                str1 = memo;
                $("#hiddenInvId").val(invoiceId);
                $("#lblBoxTitle").html(str);
                $("#boxEdit").show();
            }
        }

        $scope.editMemoSave = function () {
            var list = [];
            var invoiceId = $("#hiddenInvId").val();
            var memo = $("#txtBox").val();
            list.push('2');
            list.push(invoiceId);
            list.push(memo);
            collectorSoaProxy.savecommon(list, function () {
                $scope.saveBack(invoiceId, memo);
                $scope.editMemoClose();
            });
        }

        $scope.saveBack = function (invoiceId, memo) {

            angular.forEach($scope.gridApi.grid.rows, function (rowItem) {
                if (rowItem.entity.id == invoiceId) {
                    rowItem.entity.comments = memo;
                }
            });

        }

        $scope.editMemoClose = function () {
            $("#boxEdit").hide();
        }
        //********************** edit one memo //**********************e

        //******************************* edit batch memo *******************************s
        $scope.batcheditMemoShow = function () {
            $scope.inv = [];
            angular.forEach($scope.gridApi.selection.getSelectedRows(), function (rowItem) {
                if (rowItem.id != 0) {
                    $scope.inv.push(rowItem.id);
                }
            });

            if ($scope.inv == "" || $scope.inv == null) {
                alert("Please choose 1 invoice at least .")
            } else {
                var h = document.documentElement.clientHeight;
                var w = document.documentElement.clientWidth;
                var content = document.getElementById('boxEdit');
                var contentWidth = $('#boxEdit').css('width').replace('px', '');
                var contentHeight = $('#boxEdit').css('height').replace('px', '');
                var stop = self.pageYOffset;
                var sleft = self.pageXOffset;
                var left = w / 2 - contentWidth / 2 + sleft;
                var top = h / 2 - contentHeight / 2 + stop;
                $('#boxEditBatch').css({ 'left': left + 'px', 'top': top + 'px' });
                $('#batchtxtBox').css({ 'width': contentWidth - 20 + 'px', 'height': contentHeight - 120 + 'px' });
                var str = '';
                str = "All Selected Invoices' Memo Will Be Entirely Updated By Follow:"
                $("#batchhiddenInvId").val($scope.inv);
                $("#batchtxtBox").val("");
                $("#batchlblBoxTitle").html(str);
                $("#boxEditBatch").show();
            }
        }

        $scope.batcheditMemoSave = function () {
            var list = [];
            var invoiceIds = $("#batchhiddenInvId").val().toString();
            var memo = $("#batchtxtBox").val();
            list.push("5");
            list.push(invoiceIds);
            list.push(memo);
            collectorSoaProxy.savecommon(list, function () {
                $scope.batchsaveBack(memo);
                $scope.batcheditMemoClose();
            });
        }

        $scope.batchsaveBack = function (memo) {
            angular.forEach($scope.gridApi.selection.getSelectedRows(), function (rowItem) {
                if (rowItem.id != 0) {
                    rowItem.comments = memo + '\r\n' + rowItem.comments;
                }
            });
        }

        $scope.batcheditMemoClose = function () {
            $("#boxEditBatch").hide();
        }
        //******************************* edit batch memo *******************************e
        $scope.memoShow = function (invNum, memo, e) {
            $('#box').css({ 'left': e.pageX - 410 + 'px', 'top': e.pageY + 10 + 'px' });
            var str = '';
            str = 'Invoice :"' + invNum + '" Memo : <br>' + memo;
            $("#box").html(str);
            $("#box").show();

        }

        $scope.memoHide = function () {
            $("#box").hide();
        }


        //##########################
        //list params
        //##########################
        //*********************************** open invoice history *********************************
        $scope.openInvoiceH = function (inNum) {
            var modalDefaults = {
                templateUrl: 'app/soa/invhistory/invhistory.tpl.html',
                controller: 'invHisCL',
                size: 'lg',
                resolve: {
                    inNum: function () { return inNum; }
                }
                , windowClass: 'modalDialog'
            };

            modalService.showModal(modalDefaults, {}).then(function (result) {

            });

        }

        //******************************** days late ******************************
        $scope.calDaysLate = function (obj) {
            var aDate = obj.dueDate.toString().substring(0, 10).split('-');
            var date = new Date(aDate[0], aDate[1], aDate[2]);
            return (($scope.currentDate - date) / 86400000);
        }

        //********After ckick [ptp][payment][disput] button,refresh the value [invoiceStatus][TrackStatus][memo] to  invoiceList
        $scope.refreshListVal = function (invStatus, trackStatus, memo, ptpDate) {
            if (invStatus == '004012') {
                if (trackStatus == 'Contra') {
                    trackStatus = '018';
                } else if (trackStatus == 'Breakdown') {
                    trackStatus = '019';
                } else {
                    trackStatus = '006';
                }
            }
            angular.forEach($scope.gridApi.selection.getSelectedRows(), function (rowItem) {
                if (rowItem.id != 0) {
                    rowItem.states = invStatus;
                    rowItem.trackStates = trackStatus;
                    if (memo != null) { rowItem.comments = memo + rowItem.comments; }
                    if (ptpDate != null) { rowItem.ptpDate = ptpDate; }
                }
            });
        }

        //*************calculate invoice list checked total*************
        $scope.invoiceSum = function () {
            var total = 0;
            var currAry = [];
            var totalAry = [];
            var str = "";
            angular.forEach($scope.gridApi.selection.getSelectedRows(), function (rowItem) {
                if (currAry.indexOf(rowItem.currency) < 0) {
                    currAry.push(rowItem.currency);
                    totalAry.push(rowItem.balanceAmt);
                } else {
                    var index = currAry.indexOf(rowItem.currency);
                    total = totalAry[index] + rowItem.balanceAmt;
                    totalAry.splice(index, 1, total);
                }
            });

            for (var index in currAry) {
                str += " " + currAry[index] + ':' + $scope.formatNumber(totalAry[index], 2, 1);
            }
            $("#footcalcu").html(str);
        }

        $scope.invoiceSumBatch = function () {
            var total = 0;
            var currAry = [];
            var totalAry = [];
            var str = "";

            angular.forEach($scope.gridApi.selection.getSelectedRows(), function (rowItem) {
                if (currAry.indexOf(rowItem.currency) < 0) {
                    currAry.push(rowItem.currency);
                    totalAry.push(rowItem.balanceAmt);
                } else {
                    var index = currAry.indexOf(rowItem.currency);
                    total = totalAry[index] + rowItem.balanceAmt;
                    totalAry.splice(index, 1, total);
                }
            });
            for (var index in currAry) {
                str += " " + currAry[index] + ':' + $scope.formatNumber(totalAry[index], 2, 1);
            }
            $("#footcalcu").html(str);
        }


        //****format number
        /* 
            将数值四舍五入后格式化. 
            @param num 数值(Number或者String) 
            @param cent 要保留的小数位(Number) 
            @param isThousand 是否需要千分位 0:不需要,1:需要(数值类型); 
            @return 格式的字符串,如'1,234,567.45' 
            @type String 
        */
        $scope.formatNumber =
        function (num, cent, isThousand) {
            num = num.toString().replace(/\$|\,/g, '');
            if (isNaN(num))//检查传入数值为数值类型. 
                num = "0";
            if (isNaN(cent))//确保传入小数位为数值型数值. 
                cent = 0;
            cent = parseInt(cent);
            cent = Math.abs(cent);//求出小数位数,确保为正整数. 
            if (isNaN(isThousand))//确保传入是否需要千分位为数值类型. 
                isThousand = 0;
            isThousand = parseInt(isThousand);
            if (isThousand < 0)
                isThousand = 0;
            if (isThousand >= 1) //确保传入的数值只为0或1 
                isThousand = 1;
            sign = (num == (num = Math.abs(num)));//获取符号(正/负数) 
            //Math.floor:返回小于等于其数值参数的最大整数 
            num = Math.floor(num * Math.pow(10, cent) + 0.50000000001);//把指定的小数位先转换成整数.多余的小数位四舍五入. 
            cents = num % Math.pow(10, cent); //求出小数位数值. 
            num = Math.floor(num / Math.pow(10, cent)).toString();//求出整数位数值. 
            cents = cents.toString();//把小数位转换成字符串,以便求小数位长度. 
            while (cents.length < cent) {//补足小数位到指定的位数. 
                cents = "0" + cents;
            }
            if (isThousand == 0) //不需要千分位符. 
                return (((sign) ? '' : '-') + num + '.' + cents);
            //对整数部分进行千分位格式化. 
            for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3) ; i++)
                num = num.substring(0, num.length - (4 * i + 3)) + ',' +
                num.substring(num.length - (4 * i + 3));
            return (((sign) ? '' : '-') + num + '.' + cents);
        }
    }])
.filter('mapClass', function () {
    var typeHash = {
        'DM': 'DM',
        'CM': 'CM',
        'INV': 'INV',
        'Payment': 'Payment'
    };
    return function (input) {
        if (!input) {
            return '';
        } else {
            return typeHash[input];
        }
    };
})
.filter('mapStatus', function () {
    var typeHash = {
        '004001': 'Open',
        '004002': 'PTP',
        '004003': 'Paid',
        '004004': 'Dispute',
        '004005': 'Cancelled',
        '004006': 'Uncollectable',
        '004007': 'WriteOff',
        '004008': 'PartialPay',
        '004010': 'Broken PTP',
        '004009': 'Closed',
        '004011': 'Hold',
        '004012': 'Payment'

    };
    return function (input) {
        if (!input) {
            return '';
        } else {
            return typeHash[input];
        }
    };
})
.filter('mapTrack', function () {
    var typeHash = {
        '001': 'SOA Sent',
        '002': 'Second Reminder Sent',
        '003': 'Final Reminder Sent',
        '004': 'Dispute',
        '005': 'PTP',
        '006': 'Payment Notice Received',
        '007': 'Broken PTP',
        '008': 'First Broken Sent',
        '009': 'Second Broken Sent',
        '011': 'Hold',
        '012': 'Agency Sent',
        '013': 'Write Off',
        '014': 'Paid',
        '015': 'Bad Debit',
        '016': 'Open',
        '017': 'Close',
        '018': 'Contra',
        '019': 'Breakdown'
    };
    return function (input) {
        if (!input) {
            return '';
        } else {
            return typeHash[input];
        }
    };
});